﻿using MyModule.ManageSheep;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;

using Volo.Abp.Domain.Repositories;

namespace MyModule.Breeding
{
    public class MyModuleService : ApplicationService, IMyModuleService  
    {
        private readonly IRepository<WeighInfo, int> _weighInfoRepository;
        private readonly IRepository<WeighType, int> _repository;
        private readonly IRepository<VarietyInfo, int> _varietyInfoRepository;
        private readonly IHttpClientFactory _httpClientFactory;

        public MyModuleService(IRepository<WeighInfo, int> weighInfoRepository, IRepository<WeighType, int> repository, IRepository<VarietyInfo, int> varietyInfoRepository, IHttpClientFactory httpClientFactory)
        {
            _weighInfoRepository = weighInfoRepository;
            _repository = repository;
            _varietyInfoRepository = varietyInfoRepository;
            _httpClientFactory = httpClientFactory;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="weighInfoDTO"></param>
        /// <returns></returns>:
        
        public async Task<ResultDto<WeighInfoDTO>> PostCreateAsync(WeighInfoDTO weighInfoDTO)
        {

            var list = await _weighInfoRepository.FirstOrDefaultAsync(x=>x.Earbugles == weighInfoDTO.Earbugles);
            if (list == null)
            {
                WeighInfo weighInfo = new WeighInfo();
                weighInfo.Wdate = weighInfoDTO.Wdate;
                weighInfo.Earbugles = weighInfoDTO.Earbugles;
                weighInfo.WTid = weighInfoDTO.WTid;
                weighInfo.Weight = weighInfoDTO.Weight;
                weighInfo.Wsex = weighInfoDTO.Wsex;
                weighInfo.Vid = weighInfoDTO.Vid;
                var result = await _weighInfoRepository.InsertAsync(weighInfo);
                var listCount = ObjectMapper.Map<WeighInfo, WeighInfoDTO>(result);
                if (listCount != null)
                {
                    return new ResultDto<WeighInfoDTO>() { Code = 200, Message = "添加成功" };
                }
                else
                {
                    return new ResultDto<WeighInfoDTO>() { Code = 500, Message = "添加失败" };
                }
            }
            else 
            {
                return new ResultDto<WeighInfoDTO>() { Code = 501};
            }
        }

          
        /// <summary>
        ///删除
        /// </summary>
        /// <param name="Wid"></param>
        /// <returns></returns>
        public async Task DeleteWeighAsync(int Wid)
        {
            await _weighInfoRepository.DeleteAsync(Wid);
        }
        /// <summary>
        /// 查询全部
        /// </summary>
        /// <returns></returns>
        public async Task<List<WeighInfoTypeVarietyDTO>> GetListAsync(int  Vid,int WTid,string? Earbugles)
        {
            //int totlaCount;
            //int pageCount;

            var result = await _weighInfoRepository.GetListAsync();
            var weigh = await _repository.GetListAsync();
            var varietie = await _varietyInfoRepository.GetListAsync();
            var list = (from a in result
                       join b in weigh on a.WTid equals b.Id
                       join c in varietie on a.Vid equals c.Id
                       select new WeighInfoTypeVarietyDTO
                       {
                           Id = a.Id,
                           Wdate = a.Wdate,
                           Earbugles = a.Earbugles,
                           WTid = b.Id,
                           Weight = a.Weight,
                           Wsex = a.Wsex,
                           Vid = c.Id,
                           WTname = b.WTname,
                           Vname = c.Vname,
                       }).ToList();
            if (!string.IsNullOrEmpty(Earbugles))
            {
                list = list.Where(x => x.Earbugles == Earbugles).ToList();
            }
            if (Vid != 0)
            {
                list = list.Where(x => x.Vid == Vid).ToList();
            }
            if (WTid != 0)
            {
                list = list.Where(x => x.WTid == WTid).ToList();
            }
            //totlaCount = list.Count();
            //pageCount = (int)Math.Ceiling(totlaCount / (double)pageSize);
            //list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return list.OrderByDescending(x=>x.Id).ToList();

        }
        /// <summary>
        /// 查询全部品种
        /// </summary>
        /// <returns></returns>
        public async Task<List<VarietyInfoDTO>> GetVarietyInfoAsync()
        {
            var result = await _varietyInfoRepository.GetListAsync();
            return ObjectMapper.Map<List<VarietyInfo>, List<VarietyInfoDTO>>(result);
        }
        /// <summary>
        /// 查询全部称重类型
        /// </summary>
        /// <returns></returns>
        public async Task<List<WeighTypeDTO>> GetWeighTypeAsync()
        {
            var result = await _repository.GetListAsync();
            return ObjectMapper.Map<List<WeighType>, List<WeighTypeDTO>>(result);
        }

        /// <summary>
        /// 根据ID查询
        /// </summary>
        /// <returns></returns>
        public async Task<WeighInfoDTO> GetListAsync(int id)
        {
            var result = await _weighInfoRepository.FirstOrDefaultAsync(x=>x.Id==id);
            return ObjectMapper.Map<WeighInfo, WeighInfoDTO>(result);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="weighInfoDTO"></param>
        /// <returns></returns>
        public async Task<ResultDto<WeighInfoDTO>> UpdateWeighAsync(WeighInfoDTO weighInfoDTO)
        {

                  var result = await _weighInfoRepository.FindAsync(weighInfoDTO.Id);
                if (result == null)
                {
                    return new ResultDto<WeighInfoDTO>() { Code = 500 };
                }
                ObjectMapper.Map(weighInfoDTO, result);
                  var count = await _weighInfoRepository.UpdateAsync(result);
                  var listCount = ObjectMapper.Map<WeighInfo, WeighInfoDTO>(count);
                if (listCount != null)
                {
                    return new ResultDto<WeighInfoDTO>() { Code = 200, Message = "修改成功" };
                }
                else
                {
                    return new ResultDto<WeighInfoDTO>() { Code = 500, Message = "修改失败" };
                }

        }
        /// <summary>
        /// 体尺耳号下拉框
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<DropdownItemDto>> GetWeighEarbugles()
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/earoverbit/earoverbits");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<EarOverbit>>(jsonString);
            // 查询已使用的数据的 Id 列表
            var usedDataIds = _weighInfoRepository.GetListAsync().Result.Select(d => d.Earbugles).ToList();
            // 查询所有数据，并过滤已使用的数据
            var list = data.Where(d => !usedDataIds.Contains(d.OverbitName)).ToList();
            // 转换为 DropdownItemDto 并返回
            return list.Select(d => new DropdownItemDto { Id = d.Id, Name = d.OverbitName }).ToList();
        }

        /// <summary>
        /// 条形码
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public  string GenerateBarcodeImage(string content)
        {
            try
            {
                var filePath = Directory.GetCurrentDirectory() + @"\wwwroot\Pic" + content + ".png";
                var writer = new ZXing.Windows.Compatibility.BarcodeWriter()
                {
                    Format = ZXing.BarcodeFormat.CODE_128,
                    Options = new ZXing.Common.EncodingOptions()
                    {
                        Width = 50, // 增加宽度
                        Height = 50, // 增加高度
                        Margin = 5, // 增加边距
                        PureBarcode = false
                    }
                };
                var barcodeBitmap = writer.Write(content);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    barcodeBitmap.Save(fileStream, System.Drawing.Imaging.ImageFormat.Png);
                }
                return content + ".png";

            }
            catch (Exception ex)
            {
                Console.WriteLine("报错了:" + ex.Message);

                throw;
            }
        }
    }
}
